package com.quyeying.utils.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.quyeying.config.scheduling.CronTaskRegistrar;
import com.quyeying.config.scheduling.SchedulingRunnable;
import com.quyeying.entity.SysJob;
import com.quyeying.service.SysJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName SysJobRunner
 * @Description 实现了CommandLineRunner接口的SysJobRunner类，当spring boot项目启动完成后，加载数据库里状态为正常的定时任务
 * @Author skx
 * @Date 2021/8/9
 */
@Service
public class SysJobRunner implements CommandLineRunner {

    @Autowired
    private SysJobService sysJobService;

    @Resource
    private CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(String... args) {
        // 初始加载数据库里状态为正常的定时任务
        QueryWrapper<SysJob> wrapper = new QueryWrapper<>();
        wrapper.eq("job_status", 1);
        List<SysJob> jobList = sysJobService.list(wrapper);
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (SysJob job : jobList) {
                SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
                cronTaskRegistrar.addCronTask(task, job.getCronExpression());
            }

            System.out.println("定时任务已加载完毕...");
        }
    }
}
